#!/bin/bash
set -e

while getopts  ":b:s:p:" opts
do
        case  $opts  in
        s)
                        sample_name=$OPTARG
                        
                ;;
		p)
                        out_prefix=$OPTARG
                        
                ;;
		b)
        asemmbly=$OPTARG
        ;;
		\?)
		echo `basename $0` [-b asemmbly] [-s sample_name] [-p out_prefix] reads1.fq reads2.fq
		exit 1
		;;
        esac
done
shift $(($OPTIND - 1))


if [ $# -lt 2 ]; then
        echo `basename $0` [-b asemmbly] [-s sample_name] [-p out_prefix] reads1.fq reads2.fq
        exit 1
fi


#-----------------------------------------------
. /mnt/ilustre/app/medical/tools/.var #---------
#-----------------------------------------------

if [ -z "$asemmbly" ]; then
	asemmbly=b38
fi

echo pair-end reads 1 $1
echo pair-end reads 2 $2


echo;echo;echo start bwa mem ...
$bwa mem -M -L 1000 -t 10 -R $read_group $ref_genome \
$1 \
$2 \
> $out_prefix.sam


if
java -Xmx$java_memory -jar ${picard_path}SortSam.jar \
I=$out_prefix.sam \
O=$out_prefix.sort.bam \
SORT_ORDER=coordinate \
CREATE_INDEX=true
then
	echo;echo;echo 'picard sam->bam sort index'
else
	rm $out_prefix.sort.bai
	echo;echo;echo 'samtools sam -> bam; filter q<30; paired & mapped; sort and index;'
	samtools view -@ 10 -q30 -f 1 -F 12 -Sb $out_prefix.sam > $out_prefix.bam
	samtools sort -@ 9 -m 2G -O bam -T $out_prefix $out_prefix.bam > $out_prefix.sort.bam
fi

samtools index $out_prefix.sort.bam


